const express = require('express')
// eslint-disable-next-line no-unused-vars
const bodyParser = require('body-parser') // 创建网站服务器
const app = express()
const port = 3000

let PrjData = require('./PrjData')

let prjDataDict = {}

/*
    获取项目列表
    返回list
    code name time
 */
app.get('/api/prj/list', (req, res) => {
  res.send(req.query.code)
})

/*
    创建空项目，在当前data目录下创建空目录和空模板
    code 项目英文代号
    name 项目中文名
    /api/prj/create?code={code}&name={name}
 */
app.get('/api/prj/create', (req, res) => {
  res.send(req.query.code)
})

/*
    加载项目数据
 */
app.get('/api/prj/load', (req, res) => {
  let code = req.query.code
  if (prjDataDict[code]) {

  } else {
    prjDataDict[code] = new PrjData(code)
    prjDataDict[code].load()
  }
  res.send('load finish!')
})

/*
    重新加载项目数据
 */
app.get('/api/prj/reload', (req, res) => {
  res.send(req.query.code)
})

/*
    加载项目应用配置
 */
app.get('/api/prj/config', (req, res) => {
  res.send(req.query.code)
})

/*
    获取定义列表
 */
app.get('/api/prj/def', (req, res) => {
  let code = req.query.code
  let objCode = req.query.objCode;
  if (prjDataDict[code]) {

  } else {
    prjDataDict[code] = new PrjData(code)
    prjDataDict[code].load()
  }
  if (objCode){
    res.send(JSON.stringify(prjDataDict[code].getDef(objCode)))
  }else{
    res.send(JSON.stringify(prjDataDict[code].getDef()))
  }

})

/*
    根据code获取数据
 */
app.get('/api/prj/data', (req, res) => {
  let code = req.query.code
  let objCode = req.query.objCode
  if (prjDataDict[code]) {

  } else {
    prjDataDict[code] = new PrjData(code)
    prjDataDict[code].load()
  }
  res.send(JSON.stringify(prjDataDict[code].getData(objCode)))
})

var shapefile = require("shapefile");

app.get('/api/shp', (req, res) => {
  let url = req.query.url
  shapefile.open(url)
    .then(source => source.read()
      .then(function log(result) {
        if (result.done) return;
        res.send(JSON.stringify(result.value))
        return source.read().then(log);
      }))
    .catch(error => console.error(error.stack));

})

app.listen(port, () => {
  console.log(`server app listening at http://localhost:${port}`)
})
